const TypeModel = require('../models/TypeModel')
const CarModel = require('../models/CarModel')

const typeService = {
  getType() {
    return TypeModel.find()
  },
  getTypeByName(name) {
    return TypeModel.find({
      carName: {
        $regex: name,
      },
    })
  },
  getTypeList(category_id) {
    return TypeModel.find({
      category_id,
    }).populate('category_id')
  },
  getTypeInfo(_id) {
    return TypeModel.findById(_id)
  },
  addType(data) {
    return TypeModel.create(data)
  },
  updateType(_id, data) {
    return TypeModel.updateOne(
      {
        _id,
      },
      {
        $set: data,
      }
    )
  },
  async deleteType(_id) {
    await CarModel.deleteMany({
      type_id: _id,
    }).exec()
    return TypeModel.deleteOne({
      _id,
    })
  },
}

module.exports = typeService
